<template>
  <div class="content">
    <h1>发布管理</h1>
    <el-button type="primary" size="mini" @click="addData">新增</el-button>
    <div class="consultation-block">
      <div class="table" v-loading="tableLoading">
        <el-table size="mini" :data="tableDataFilter" style="width: 100%">
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column prop="jobName" label="职位名称"> </el-table-column>
          <el-table-column prop="type" label="职位类型"> </el-table-column>
          <el-table-column prop="salary" label="薪资"> </el-table-column>
          <el-table-column prop="jobLocation" label="职位地点"> </el-table-column>
          <el-table-column prop="xueli" label="学历"> </el-table-column>
          <el-table-column prop="tags" label="标签" :formatter="formatTags"> </el-table-column>
          <el-table-column prop="experience" label="经验"> </el-table-column>
          <el-table-column prop="category" label="种类"> </el-table-column>
          <el-table-column prop="other" label="其他信息"> </el-table-column>
          <el-table-column prop="examine" label="审核通过" :formatter="formatEx"> </el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                type="warning"
                size="mini"
                @click="updateData(scope.row)"
                >修改</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="deleteData(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="pageNum"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="isVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        :model="form"
        status-icon
        :rules="rules"
        ref="form"
        label-width="120px"
        class="demo-form"
      >
        <el-form-item label="职位名称" prop="jobName">
          <el-input type="text" v-model="form.jobName"></el-input>
        </el-form-item>
        <el-form-item label="岗位描述" prop="jobDesc">
          <el-input type="textarea" :rows="4" v-model="form.jobDesc"></el-input>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-checkbox-group v-model="form.tags">
            <el-checkbox :key="index" v-for="(tag, index) in jobTags" :label="tag"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="学历" prop="xueli">
          <el-select v-model="form.xueli" placeholder="请选择">
            <el-option
              v-for="item in xuelis"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="薪资" prop="salary">
          <el-select v-model="form.salary" placeholder="请选择">
            <el-option
              v-for="item in jobSalarys"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择">
            <el-option
              v-for="item in jobCategories"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option
              v-for="item in jobTypes"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经验" prop="experience">
          <el-select v-model="form.experience" placeholder="请选择">
            <el-option
              v-for="item in jobExperiences"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位地点" prop="jobLocation">
          <el-select v-model="form.jobLocation" placeholder="请选择">
            <el-option
              v-for="item in jobLocations"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="营业执照" prop="companyCard">
          <div v-if="form.companyCard" class="img-blocks">
            <div style="position: relative">
              <img :src="form.companyCard" style="width: 80px" />
            </div>
          </div>
          <el-upload
            class="avatar-uploader"
            :action="'/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <el-button v-if="form.examine !== 'false'">上传</el-button>
            <el-button type="danger" v-if="form.examine === 'false'">审核未通过，重新上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="公司环境" prop="companyPics">
          <div v-if="form.companyPics" class="img-blocks">
            <div
              v-for="(img, index) in form.companyPics"
              :key="index"
              style="position: relative"
            >
              <img :src="img" style="width: 80px" />
              <i @click="deleteImg(index)" class="el-icon-circle-close"></i>
            </div>
          </div>
          <el-upload
            class="avatar-uploader"
            :action="'/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess2"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserInfo,addJob,getXuelis,getJob, deleteJob,getJobByUser,updateJob,getJobSalary,getJobTags,getJobExperience,getJobLocation,getJobTypes } from "../service.js";
export default {
  name: "publish",
  beforeCreate() {
    getJobSalary().then(res => {
      this.jobSalarys = res.code === 200 ? res.data : []
    })
    getJobTags().then(res => {
      this.jobTags = res.code === 200 ? res.data : []
    })
    getJobExperience().then(res => {
      this.jobExperiences = res.code === 200 ? res.data : []
    })
    getJobLocation().then(res => {
      this.jobLocations = res.code === 200 ? res.data : []
    })
    getJobTypes().then(res => {
      this.jobTypes = res.code === 200 ? res.data : []
    })
    getXuelis().then(res => {
      this.xuelis = res.code === 200 ? res.data : []
    })
  },
  mounted() {
    // 查询个人资料
    if (localStorage.getItem("meiyaWebInfo")) {
      this.userInfo = JSON.parse(localStorage.getItem("meiyaWebInfo"))
      getUserInfo(this.userInfo._id).then(res => {
        this.userInfo = res.data
        this.refreshTable();
      })
    }
  },
  data() {
    return {
      userInfo: {},
      tableData: [],
      tableDataFilter: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tableLoading: false,
      isVisible: false,
      dialogTitle: "",
      form: {
        jobName: "",
        jobDesc: "",
        tags: [],
        salary: '',
        experience: '',
        jobLocation: '',
        companyCard: '',
        xueli: '',
        category: '',
        companyPics: []
      },
      rules: {
        jobName: [{ required: true, message: "请输入", trigger: "blur" }],
        jobDesc: [{ required: true, message: "请输入", trigger: "blur" }],
        salary: [{ required: true, message: "请选择", trigger: "blur" }],
        type: [{ required: true, message: "请选择", trigger: "blur" }],
        experience: [{ required: true, message: "请选择", trigger: "blur" }],
        tags: [{ required: true, message: "请选择", trigger: "change" }],
        xueli: [{ required: true, message: "请选择", trigger: "change" }],
        category: [{ required: true, message: "请选择", trigger: "change" }],
        jobLocation: [{ required: true, message: "请选择", trigger: "change" }],
        companyCard: [{ required: true, message: "请上传", trigger: "change" }],
        companyPics: [{ required: true, message: "请上传", trigger: "change" }],
      },
      funList: [],
      jobSalarys: [],
      jobTags: [],
      jobExperiences: [],
      jobLocations: [],
      jobTypes: [],
      xuelis: [],
      jobCategories: ['全职', '兼职', '校招']
    };
  },
  methods: {
    naviData() {
      this.tableDataFilter = this.tableData.slice(
        (this.pageNum - 1) * this.pageSize,
        this.pageSize * this.pageNum
      );
    },
    handleAvatarSuccess(info) {
      this.form.pics.push(info.url);
    },
    addUser() {
      this.isVisible = true;
      this.form = {
        username: "",
        pass: "",
        checkPass: "",
        title: "",
        column: "",
      };
      this.dialogTitle = "新建用户";
    },
    handleClose() {
      this.isVisible = false;
    },
    handleCurrentChange(index) {
      this.pageNum = index
      this.naviData()
    },
    submitForm(formName) {
      let form = {
        ...this.form,
        companyPics: JSON.stringify(this.form.companyPics),
        tags: JSON.stringify(this.form.tags),
        publisherId: this.userInfo._id
      };
      if (form.examine === 'false') {
        form.examine = ''
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.form._id) {
            addJob(form).then((res) => {
              console.log(res);
              if (res.code === 200) {
                this.$message.success("新增成功");
                this.isVisible = false;
                this.refreshTable();
              }
            });
            return;
          }
          updateJob(this.form._id, {
            jobName: form.jobName,
            jobLocation: form.jobLocation,
            companyPics: form.companyPics,
            jobDesc: form.jobDesc,
            tags: form.tags,
            experience: form.experience,
            other: form.other,
            salary: form.salary,
            xueli: form.xueli,
            examine: form.examine
          }).then((res) => {
            if (res.code === 200) {
              this.$message.success("编辑成功");
              this.refreshTable();
              this.isVisible = false;
            }
          });
        } else {
          return false;
        }
      });
    },
    addData() {
      if (!this.userInfo.companyName || !this.userInfo.jobName) {
        this.$message.error('请先完善个人资料')
        return
      }
      this.dialogTitle = "新增";
      this.isVisible = true;
    },
    refreshTable() {
      getJobByUser({
        publisherId: this.userInfo._id
      }).then((res) => {
        this.tableData = res.code === 200 ? res.data : [];
        for (let item of this.tableData) {
          item.tags = JSON.parse(item.tags)
        }
        this.total = this.tableData.length;
        this.naviData()
      });
    },
    updateData(row) {
      this.form = {
        ...row
      };
      if (this.form.companyPics) {
        this.form.companyPics = JSON.parse(this.form.companyPics)
      }
      this.dialogTitle = "修改";
      this.isVisible = true;
    },
    deleteData(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteJob(row._id).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              if (this.tableDataFilter.length == 1) {
                this.pageNum--
              }
              this.refreshTable();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    formatTags(row) {
      if (row.tags) {
        return row.tags.join(',')
      }
    },
    formatEx(row) {
      if (row.examine) {
        if (row.examine === 'true') {
          return '审核通过'
        } else {
          return '审核未通过'
        }
      } else {
        return '未审核'
      }
    },
    deleteImg(index) {
      this.form.companyPics.splice(index, 1);
    },
    handleAvatarSuccess(rs) {
      this.form.companyCard = rs.url; 
    },
    handleAvatarSuccess2(rs) {
      this.form.companyPics.push(rs.url);
    }
  },
};
</script>

<style lang="scss" scoped>
h1 {
  text-align: center;
  margin: 30px auto;
}
.content {
  width: 1200px;
  margin: 0 auto;
  min-height: 80vh;
}
.pagination {
  text-align: center;
  margin-top: 30px;
}
</style>
